//app.js
const Parser = require('/utils/dom-parser.js')
var md5 = require('/utils/md5.js')
let _globalData = {
  userInfo: null,
  toname: '',
  wishes: '',
  // in case
  // 在更多页面中选则某条祝福话后，直接覆盖上面的wishes字段,而用户却在自定义页面选择了取消或返回
  tempwishes: '',
  temptoname: '',
  tempnickname: ''
}


App({
  onLaunch: function (options) {
    var that = this
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var scene = decodeURIComponent(options.scene)
    console.log('使用场景:' + scene)
    this.globalData.scene = scene
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          if (!that.globalData.code) {
            that.globalData.code = res.code;
            // 获取用户信息
           /* wx.getSetting({
              success: res11 => {
                //var that = this
                console.log('获取用户设置:')
                console.log(res11)
                if (!('scope.userInfo' in res11.authSetting)) {
                  wx.showModal({
                    title: '授权提示',
                    content: '星辰祝福将要获取用户昵称,是否继续？',
                    success: function (res) {
                      if (res.confirm) {
                        console.log('点击了确定')
                        wx.openSetting({
                          success: (res0) => {
                            console.log(res0.authSetting)
                            if (res0.authSetting['scope.userInfo']) {
                              that.getUserInfo()
                            }
                          }
                        })
                      } else {
                        wx.showModal({
                          title: '未授权提示',
                          content: '用户未授权,无法使用送祝福、绕口令功能',
                          showCancel: false,
                        })
                      }
                    }
                  })
                } else {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                  that.getUserInfo()
                }
              }
            })*/
            if (!that.globalData.userInfo){
              that.getUserInfo()
            }
            if (!that.globalData.openid) {
              wx.request({
                method: 'post',
                url: 'https://wsh.weyifeng.com/wx/getOpenid', //仅为示例，并非真实的接口地址
                data: {
                  appId: that.globalData.appId,
                  appSecret: that.globalData.appSecret,
                  code: res.code
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded' // 默认值
                },
                success: function (res) {
                  console.log('获取用户信息时返回的结果是:')
                  console.log(res.data)
                  if (res.data.success) {
                    that.globalData.openid = res.data.wxUser.openid
                    that.globalData.localIP = res.data.clientIP

                   
                    //从数据库获取用户信息,判断是否为vip
                    wx.request({
                      method: 'post',
                      url: 'https://wsh.weyifeng.com/findisVip',
                      data: { 'openid': that.globalData.openid },
                      header: { 'content-type': 'application/x-www-form-urlencoded' },
                      success: function (r) {
                        console.log("-----------------------------")
                        console.log(r.data)
                        that.globalData.isVip = r.data.isVIP
                      }
                    })
                  } else {
                    console.log('app.js wx.login获取用户openid失败')
                  }
                }
              })
            }
            console.log('全局变量:')
            console.log(that.globalData)
          }
        } else {
          wx.redirectTo({
            url: 'pages/toptaber/toptaber'
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    appId: 'wx43b4fbf2621c01c3',
    appSecret: '2a1fc49556cf05bf7f470981f5f87ba8',
    code: '',
    openid: '',
    mch_id: '1489652852',
    key: 'dho23hl5ojgsdj56jk90H898adf45jJl',
    localIP: '',
    scene: '',
    toIndex: 0,
    imgid: '',
    imgurl: '',
    imgadio: '',
    tempFilePaths: '',
    tempFilePathsID: '',
    bgImages: '',
    bgImagesID: '',
    isVip: '',
    wishName:'',
    istwoOnload:'',
    audioPlay:false
  },
  /**
   * 读取与修改运行时全局变量的方法
   */
  getUserInfos: function (cb) {
    var that = this
    if (_globalData.userInfo) {
      typeof cb == "function" && cb(_globalData.userInfo)
    } else {
      //调用登录接口 
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              _globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(_globalData.userInfo)
            }
          })
        }
      })
    }
  },
    setUserInfo: function (userInfo) {
    var that = this;
    if (_globalData.userInfo) {
      _globalData.userInfo = userInfo;
      return;
    }
    that.getUserInfo();
  },
  getTempNickName: function () {
    return _globalData.tempnickname
  },
  setTempNickName: function (nickname) {
    _globalData.tempnickname = nickname;
  },
  clearTempNickName: function () {
    _globalData.tempnickname = '';
  },
  getToName: function (isTemp) {
    if (isTemp) {
      return _globalData.temptoname
    } else {
      return _globalData.toname;
    }

  },
  setToName: function (toname, isTemp) {
    if (isTemp) {
      _globalData.temptoname = toname;
    } else {
      _globalData.toname = toname;
    }
  },
  clearTempToName: function () {
    _globalData.temptoname = '';
  },
  setWishes: function (content, isTemp) {
    if (isTemp) {
      _globalData.tempwishes = content;
    } else {
      _globalData.wishes = content;
    }
  },
  getWishes: function (isTemp) {
    if (isTemp) {
      return _globalData.tempwishes;
    }
    return _globalData.wishes;
  },
  clearWishes: function (isTemp) {
    if (isTemp) {
      _globalData.tempwishes = '';
    } else {
      _globalData.wishes = '';
    }

  },
  setimgid: function (content, isTemp) {
    if (isTemp) {
      this.globalData.imgid = content;
    } else {
      this.globalData.imgid = content;
    }
  }, setimgurl: function (content, isTemp) {
    if (isTemp) {
      this.globalData.imgurl = content;
    } else {
      this.globalData.imgurl = content;
    }
  }, setimgadio: function (content, isTemp) {
    if (isTemp) {
      this.globalData.imgadio = content;
    } else {
      this.globalData.imgadio = content;
    }
  }, settempFilePaths: function (content) {
    this.globalData.tempFilePaths = content;
  }, settempFilePathsID: function (content) {
    this.globalData.tempFilePathsID = content;
  }, setAudioPlay: function (audioCtx){
    //var audioCtx = wx.createAudioContext('myAudio')
    audioCtx.play()
  },
  //支付成为会员(官方通道)
  vipPay:function(){
    var that = this
    var orderNo = parseInt(Math.random() * Math.pow(10, 15))
    var money = 1
    var goodsName = 'vip费'

    var moneyNum = parseInt(100 * parseFloat(money))
    var body = encodeURIComponent(goodsName)
    var appid = that.globalData.appId
    var mch_id = that.globalData.mch_id
    var randomStr = Math.random().toString().substr(2)
    var openid = that.globalData.openid
    var orderNo = parseInt(Math.random() * Math.pow(10, 15))
    var key = that.globalData.key

    // var avatarUrl = app.globalData.userInfo ? app.globalData.userInfo.avatarUrl : '/img/userIcon.png'
      //  wx.navigateTo({
      //    url: '../relay/relay?avatarUrl=' + avatarUrl + '&question=' + question + '&result=' + result + '&money=' + money + '&num=' + num,
      //  })

      var notify_url = 'https://wsh.weyifeng.com/wx/PayNotice'
      //个人测试用http://myhsk.51vip.biz,服务器测试用https://api.weyifeng.com
      var sourceStr = 'appid=' + appid + '&body=' + body + '&mch_id=' + mch_id + '&nonce_str=' + randomStr + '&notify_url=' + notify_url + '&openid=' + openid + '&out_trade_no=' + orderNo + '&spbill_create_ip=' + that.globalData.localIP + '&total_fee=' + moneyNum + '&trade_type=JSAPI&key=' + key

      var sign = md5.hexMD5(sourceStr);
      console.log(sourceStr)
      console.log('sign:' + sign)

      var formData = "<xml>"
      formData += "<appid>" + appid + "</appid>" //appid 
      formData += "<body>" + body + "</body>"    //标题
      formData += "<mch_id>" + mch_id + "</mch_id>" //商户号 
      formData += "<nonce_str>" + randomStr + "</nonce_str>" //随机字符串，不长于32位。 
      formData += "<notify_url>" + notify_url + "</notify_url>" //异步接收微信支付结果通知的回调地址
      formData += "<openid>" + openid + "</openid>"  //用户Id
      formData += "<out_trade_no>" + orderNo + "</out_trade_no>" //商户订单号
      formData += "<spbill_create_ip>" + that.globalData.localIP + "</spbill_create_ip>"
      formData += "<total_fee>" + moneyNum + "</total_fee>" //金额
      formData += "<trade_type>JSAPI</trade_type>"  //公共号支付
      formData += "<sign>" + sign + "</sign>"//签名
      formData += "</xml>"
      console.log(formData)

      wx.request({
        method: 'post',
        url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
        data: formData,
        header: {
          'content-type': 'application/xml; charset=utf-8'
        },
        method: "POST",
        success: function (res) {
          console.log(res.data)
          var xml = res.data
          var XMLParser = new Parser.DOMParser()
          var doc = XMLParser.parseFromString(xml)
          var codeEL = doc.getElementsByTagName('return_code')[0]
          var resultCode = ''
          var msg = ''
          if (codeEL) {
            resultCode = codeEL.firstChild.nodeValue
            var msgEl = doc.getElementsByTagName('result_code')[0]
            if (msgEl) {
              msg = msgEl.firstChild.nodeValue
            } else {
              msg = '未知错误,返回参数为空!'
            }
          }
            var prepay_idEl = doc.getElementsByTagName('prepay_id')[0]
            var nonceStrEl = doc.getElementsByTagName('nonce_str')[0]
            var prepayid = prepay_idEl ? prepay_idEl.firstChild.nodeValue : ''
            var nonceStr = nonceStrEl ? nonceStrEl.firstChild.nodeValue : ''
            var timeStamp = Date.parse(new Date()) / 1000
            console.log('时间戳' + timeStamp)
            var paySign_source = 'appId=' + appid + '&nonceStr=' + nonceStr + '&package=prepay_id=' + prepayid + '&signType=MD5&timeStamp=' + timeStamp + '&key=' + key
            var paySign = md5.hexMD5(paySign_source)
            //console.log('加密前:' + paySign_source)
            //console.log('加密后:'+paySign)
            var userisnull=true;
            if (!that.globalData.userInfo){
              that.getUserInfo()
              if (!that.globalData.userInfo){
                wx.openSetting({
                  success:function(){
                    that.getUserInfo()
                  }
                })  
              }
              if (!that.globalData.userInfo){
                userisnull=true
              }else{
                userisnull=false
              }
            }else{
              userisnull=false
            }
            if(!userisnull){
            wx.requestPayment(
              {
                'timeStamp': timeStamp + '',
                'nonceStr': nonceStr,
                'package': 'prepay_id=' + prepayid,
                'signType': 'MD5',
                'paySign': paySign,
                success: function (resa) {
                  console.log('付款后返回的结果:')
                  console.log(resa)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'success',
                    duration: 3000
                  })
                  console.log("openid----------:" + that.globalData.openid + 'openid:=====:' + openid)
                  console.log("that.globalData.isVip-----------:1" + that.globalData.isVip)
                  that.globalData.isVip = '1'
               
                  //支付成功后修改vip状态并添加订单
                  wx.request({
                    method: 'post',
                    url: 'https://wsh.weyifeng.com/turnVip',
                    data: { 
                      'openid': that.globalData.openid,
                      'payMoney': moneyNum,
                      'payName': that.globalData.userInfo.nickName,
                      'inOrderNo': orderNo,
                      'payGoodsName': goodsName
                    },
                    header: { 'content-type': 'application/x-www-form-urlencoded' },
                    success:function(e){
                      that.globalData.isVip='1'
                      console.log(e.data)
                    }
                  })
                  console.log("that.globalData.isVip-----------:2" + that.globalData.isVip)
                },
                fail: function (res) {
                  console.log(res)
                  var msg1 = '';
                  if (res.err_desc) {
                    msg1 = res.err_desc
                  } else if (res.errMsg) {
                    msg1 = res.errMsg
                    if (msg1 == 'requestPayment:fail cancel') {
                      msg1 = '支付取消了!'
                    }
                  }
                  wx.showModal({
                    title: '提示',
                    content: '抱歉,支付' + money + '元失败啦!原因：' + msg1,
                    showCancel: false
                  })
                },
                complete: function (res) {
                }
              })
        }else{
              wx.showModal({
                title: '提示',
                content: '异常',
                showCancel: false
              })
        }
        }, fail: function (e2) {
          wx.showToast({
            title: '支付请求失败',
            icon: 'warn',
            duration: 2000
          })
        }
      })
  },getUserInfo:function(){
    var that=this
    wx.getUserInfo({
      success: resa => {
        // 可以将 res 发送给后台解码出 unionId
        this.globalData.userInfo = resa.userInfo
        console.log('用户详细信息:')
        console.log(resa.userInfo)
        console.log('openid:' + that.globalData.openid)
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(resa)
        }
        if (that.globalData.userInfo) {
          wx.request({
            method: 'post',
            url: 'https://wsh.weyifeng.com/addWXUser',
            data: {
              openid: that.globalData.openid,
              gender: that.globalData.userInfo.gender,
              avatarUrl: that.globalData.userInfo.avatarUrl,
              contry: that.globalData.userInfo.country,
              province: that.globalData.userInfo.province,
              city: that.globalData.userInfo.city,
              nickName: that.globalData.userInfo.nickName
            },
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: function (e) {
              console.log(e.data)
            }
          })
        } else {
          wx.showModal({
            title: '授权提示',
            content: '星辰祝福将要获取用户地理位置,是否继续？',
            success: function (res) {
            }
          })
        }
      }
    })
  }
  //支付成为会员(兴业通道)
  /*vipPay: function () {
    var that = this
    var orderNo = parseInt(Math.random() * Math.pow(10, 15))
    var money = 100
    var getNum = 1

    if (!orderNo) {
      wx.showModal({
        content: '订单号不能为空!',
        showCancel: false
      })
    } else if (money <= 0) {
      wx.showModal({
        content: '对不起,您输入的单价有误!',
        showCancel: false
      })
    } else {

      var goodsName='vip费'
      var appid = that.globalData.appId
      var openid = that.globalData.openid
      var mch_id = that.globalData.mch_id
      var key = that.globalData.key
      var body = encodeURIComponent(goodsName)
      var moneyNum = money * parseInt(getNum)
      console.log('moneyNum:' + moneyNum + ',body:' + body)
      var moneySumTxt = (moneyNum / 100).toFixed(2)

      wx.showModal({
        content: '您好,您将总共支付￥' + moneySumTxt + '元',
        success: function (res) {
          if (res.confirm) {
            console.log('用户确认支付' + moneySumTxt + '元')
            var url = "https://wsh.weyifeng.com/XY/getPayInfo"
            var randomStr = Math.random().toString().substr(2)
            //body注意中文转义
            var sourceStr = 'body=' + body + '&charset=UTF-8&is_minipg=1&is_raw=1&mch_create_ip=' + that.globalData.localIP + '&mch_id=' + mch_id + '&nonce_str=' + randomStr + "&notify_url=http://myhsk.51vip.biz/PayNotice&out_trade_no=" + orderNo + "&service=pay.weixin.jspay&sub_appid=" + appid + "&sub_openid=" + openid + "&total_fee=" + moneyNum + "&key=" + key
            var sign = md5.hexMD5(sourceStr);
            console.log('param:' + sourceStr)
            console.log('sign:' + sign)
            wx.request({
              url: url, //仅为示例，并非真实的接口地址
              method: 'GET',
              data: {
                service: 'pay.weixin.jspay',
                charset: 'UTF-8',
                mch_id: mch_id,
                is_raw: '1',
                is_minipg: '1',
                out_trade_no: orderNo,
                body: body,
                sub_openid: openid,
                sub_appid: appid,
                total_fee: moneyNum,
                mch_create_ip: that.globalData.localIP,
                notify_url: 'http://myhsk.51vip.biz/PayNotice',
                nonce_str: randomStr,
                key: key,
                sign: sign
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded; charset=utf-8'
              },
              success: function (res) {
                console.log(res.data)
                if (!res) {
                  wx.showModal({
                    content: '支付失败,原因：返回结果为空!',
                    showCancel: false
                  })
                } else if (!res.data.pay_info) {
                  wx.showModal({
                    content: '支付失败,原因：' + res.data.message,
                    showCancel: false
                  })
                } else {
                  var payInfo = JSON.parse(res.data.pay_info)
                  wx.requestPayment(
                    {
                      'timeStamp': payInfo.timeStamp,
                      'nonceStr': payInfo.nonceStr,
                      'package': payInfo.package,
                      'signType': payInfo.signType,
                      'paySign': payInfo.paySign,
                      'success': function (res) {
                        console.log(res)
                        wx.showModal({
                          content: '恭喜您成功支付' + moneySumTxt + '元',
                          showCancel: false
                        })
                        that.clear()
                      },
                      'fail': function (res) {
                        console.log(res)
                        var msg = '';
                        if (res.err_desc) {
                          msg = res.err_desc
                        } else if (res.errMsg) {
                          msg = res.errMsg
                          if (msg == 'requestPayment:fail cancel') {
                            msg = '支付取消了!'
                          }
                        }
                        wx.showModal({
                          content: '抱歉,支付' + moneySumTxt + '元失败啦!原因：' + msg,
                          showCancel: false
                        })
                        that.clear()
                      },
                      'complete': function (res) {
                      }
                    })
                }
              }
            })
          }
        }
      })
    }
  }*/
})